package com.kingyun.gpsinspection.purificationservice.services.activitiservice.ext.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.kingyun.gpsinspection.purificationservice.common.activiti.ActivitiMeditorFactory;
import com.kingyun.gpsinspection.purificationservice.common.activiti.ApplicationContextUtils;
import com.kingyun.gpsinspection.purificationservice.services.activitiservice.ext.Meditor.MeditorFactory;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 工作流封装数据工具类
 */
public final class ActivitiMakeDataUtil{

    private static Logger _log = LoggerFactory.getLogger(ActivitiMakeDataUtil.class);
    private static HistoricProcessInstanceQuery historicProcessInstanceQuery;
    static{
         HistoryService historyService = (HistoryService) ApplicationContextUtils.getBean("historyService");
         historicProcessInstanceQuery = historyService.createHistoricProcessInstanceQuery();
    }




    /**
     * 封装流程实例数据
     * @param historicProcessInstances
     * @return
     */
    public static List<JSONObject> makeHistoricProcessInstancePageData(List<HistoricProcessInstance> historicProcessInstances){
        List<JSONObject> result = Lists.newArrayList();
        if(historicProcessInstances !=null && historicProcessInstances.size()>0){
            for(HistoricProcessInstance historicProcessInstance:historicProcessInstances){
                result.add(initHistoricProcessInstanceData(historicProcessInstance));
            }
        }

        return result;
    }

    private static JSONObject initHistoricProcessInstanceData(HistoricProcessInstance historicProcessInstance){
        JSONObject TaskObj= new JSONObject();
        try{

            //流程实例id
            TaskObj.put("processInstanceId",historicProcessInstance.getId());
            //流程实例名称
            TaskObj.put("processInstanceName",historicProcessInstance.getName());


            // 流程定义id
            TaskObj.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
            // 流程开始时间
            TaskObj.put("startTime",DateFormatUtils.format(historicProcessInstance.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
            // 流程结束时间
            if(historicProcessInstance.getEndTime()!=null){
                TaskObj.put("endTime", DateFormatUtils.format(historicProcessInstance.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
            }else{
                TaskObj.put("endTime","");
            }


            // 流程经历时长
            if(historicProcessInstance.getDurationInMillis()!=null){
                TaskObj.put("duraTime",formatTime(historicProcessInstance.getDurationInMillis()));
            }else{
                TaskObj.put("duraTime","");
            }

            //任务发起人
            TaskObj.put("startUser",historicProcessInstance.getStartUserId());

            //任务类型
            TaskObj.put("taskType",historicProcessInstance.getName());

        }catch (Exception e){
            _log.error("封装流程实例数据失败",e);
        }
        return  TaskObj;
    }

        /*
     * 毫秒转化时分秒毫秒
     */
    private  static String formatTime(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if(day > 0) {
            sb.append(day+"天");
        }
        if(hour > 0) {
            sb.append(hour+"小时");
        }
        if(minute > 0) {
            sb.append(minute+"分");
        }
        if(second > 0) {
            sb.append(second+"秒");
        }
        if(milliSecond > 0) {
            sb.append(milliSecond+"毫秒");
        }
        return sb.toString();
    }


    /**
     * 封装分页的待办任务数据
     * @param todoTasks
     * @return
     */
    public static List<JSONObject> makeTodoTaskPageData(List<Task> todoTasks) {
        List<JSONObject> result = Lists.newArrayList();
        if(todoTasks !=null && todoTasks.size()>0){
            for(Task task:todoTasks){
                result.add(initTaskData(task));
            }
        }

        return result;
    }



    /**
     * 封装分页的已办任务数据
     * @param doneTasks
     * @return
     */
    public static List<JSONObject> makeDoneTaskPageData(List<HistoricTaskInstance> doneTasks){
        List<JSONObject> result = Lists.newArrayList();
        if(doneTasks !=null && doneTasks.size()>0){
            for(HistoricTaskInstance task:doneTasks){
                result.add(initTaskData(task));
            }
        }
        return result;
    }


    private static JSONObject initTaskData(TaskInfo task){
        JSONObject TaskObj= new JSONObject();
        try{


            //任务ID
            TaskObj.put("taskId",task.getId());
            //任务名称
            TaskObj.put("taskName",task.getName());
            //任务办理人
          /*  TaskObj.put("assigneePerson",employeeMapper.queryByKeyId(task.getAssignee()).getName());*/
            // 任务key
            TaskObj.put("taskKey", task.getTaskDefinitionKey());
            // 流程定义ID
            TaskObj.put("processDefinitionId", task.getProcessDefinitionId());
            // 流程实例ID
            TaskObj.put("processInstanceId", task.getProcessInstanceId());
            // 任务开始时间
            TaskObj.put("createTime", DateFormatUtils.format(task.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            // 逾期时间
            if(task.getDueDate()!=null){
                TaskObj.put("dueDate", DateFormatUtils.format(task.getDueDate(), "yyyy-MM-dd HH:mm:ss"));
            }else{
                TaskObj.put("dueDate", "");
            }

            //任务发起人

             HistoricProcessInstance historicProcessInstance = ActivitiMeditorFactory.getInstance().createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
             TaskObj.put("startUser", MeditorFactory.getInstance().createStartUserIdAndNameStr(historicProcessInstance.getStartUserId()));

             TaskObj.put("businessKey",historicProcessInstance.getBusinessKey());
           // ProcessDefinition processDefinition = ActivitiMeditorFactory.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
            //任务类型
            TaskObj.put("taskType",historicProcessInstance.getProcessDefinitionName());

            // 任务描述
            TaskObj.put("description", task.getDescription());
            // owner
            TaskObj.put("owner", task.getOwner());




        }catch (Exception e){
            _log.error("封装任务数据失败",e);
        }
        return  TaskObj;

    }



    /**
     * 封装分页的流程定义的数据
     * @param processDefinitions
     * @return
     */
    public  static List<JSONObject> makeProcessDefinitionData(List<ProcessDefinition> processDefinitions){
        List<JSONObject> result = Lists.newArrayList();
        if(processDefinitions !=null && processDefinitions.size()>0){
            for(ProcessDefinition processDefinition:processDefinitions){
                result.add(initProdessDefinitionData(processDefinition));
            }
        }
        return result;
    }


    private static JSONObject initProdessDefinitionData(ProcessDefinition processDefinition){
        JSONObject processDefinitionObj= new JSONObject();
        try{
            //流程定义Id
            processDefinitionObj.put("id",processDefinition.getId());
            //流程定义名称
            processDefinitionObj.put("name",processDefinition.getName());

            /**
             * 流程定义种类
             */
            processDefinitionObj.put("category",processDefinition.getCategory());

            /**
             * 流程定义描述
             */
            processDefinitionObj.put("desc",processDefinition.getDescription());

            /**
             * 流程定义版本号
             */
            processDefinitionObj.put("version",processDefinition.getVersion());


            /**
             * 流程定义key
             */
            processDefinitionObj.put("key",processDefinition.getKey());

            /**
             * 流程定义发布ID
             */
            processDefinitionObj.put("deploementId",processDefinition.getDeploymentId());

        }catch (Exception e){
            _log.error("封装任务数据失败",e);
        }
        return  processDefinitionObj;

    }


}
